import axios from "axios";
import BMF from "browser-md5-file";
import dayjs from "dayjs";
import ExifReader from "exifreader";
var customParseFormat = require("dayjs/plugin/customParseFormat");
const bmf = new BMF();

export function getFileMD5(file: File): Promise<string> {
	return new Promise((resolve, reject) => {
		bmf.md5(file, (err: any, md5: string) => {
			if (err) {
				reject(err);
			} else {
				resolve(md5);
			}
		});
	});
}
/**
 * 获取文件拍摄时间
 * @param file File
 * @returns
 */
export function getImageTime(file: File): Promise<string> {
	return new Promise(async (resolve, reject) => {
		try {
			const tags = await ExifReader.load(file);
			let time =
				(tags["DateTimeOriginal"] as any)?.value[0] ||
				(tags["DateTimeOriginal"] as any)?.value[0];
			dayjs.extend(customParseFormat);
			if (time && dayjs(time, "YYYY:MM:DD HH:mm:ss").isValid()) {
				resolve(dayjs(time, "YYYY:MM:DD HH:mm:ss").format("YYYY-MM-DD"));
			} else {
				resolve(dayjs().format("YYYY-MM-DD"));
			}
		} catch (error) {
			console.warn("未找到患者拍摄时间,已使用上传时间记录");
			resolve(dayjs().format("YYYY-MM-DD"));
		}
	});
}

/**
 * 获取文件后缀(不带.)
 * @param file File
 * @returns
 */
export function getFileExpand(file: File) {
	let name = file.name.split(".");
	let ext = name[name.length - 1].toLowerCase();
	return ext;
}

/**
 * 图片压缩
 * @param file File
 * @param quality 压缩质量
 * @returns
 */
export function compressImage(file: File, quality: number = 0.8) {
	return new Promise((resolve, reject) => {
		const reader = new FileReader();
		reader.readAsDataURL(file);
		reader.onload = (e) => {
			const img = new Image();
			img.src = e.target?.result as string;
			img.onload = () => {
				const canvas = document.createElement("canvas");
				const ctx = canvas.getContext("2d");
				if (!ctx) {
					reject();
					return;
				}
				canvas.width = img.width;
				canvas.height = img.height;
				ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
				// 转为blob
				canvas.toBlob(
					(blob) => {
						if (blob) {
							resolve(blob);
						} else {
							reject();
						}
					},
					"image/jpeg",
					quality
				);
			};
		};
	});
}
